﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;

using System.Xml.Serialization;
using System.IO;
using System.Globalization;

using System.Threading;
using System.Data.SQLite;


namespace Maniac
{
    public partial class MainForm : Form
    {
        private DayMatrix ivdDayMatrix = null;

        private WatchList ivwWatchList = null;
        private WatchList ivwDowWatchList = null;
        private WatchList ivwNasdaq100WatchList = null;
        private WatchList ivwRecentWatchList = null;

		private DayType ivtDayType;
       

        private DateTime ivdSelectionStart = DateTime.Now;
        private DateTime ivdSelectionEnd = DateTime.Now.AddDays(7);

        private SecuritySort ivsSort = SecuritySort.IndexDown;

        private DayAggregateControl ivdPriorControl;
		
        public MainForm()
        {
            InitializeComponent();

            ivdDayMatrix = new DayMatrix();

            ivwWatchList = new WatchList();
			ivwWatchList.Type = WatchListType.Recent;

            ivwDowWatchList = new WatchList();
            ivwDowWatchList.Type = WatchListType.Index;
            initializeDowWatchlist();

            ivwNasdaq100WatchList = new WatchList();
            ivwNasdaq100WatchList.Type = WatchListType.Index;
            initiateIndexWatchlist();

            ivwRecentWatchList = new WatchList();
            ivwRecentWatchList.Type = WatchListType.Recent;
			
			ivtDayType = DayType.Calendar;            
        }
        private void initiateIndexWatchlist()
        {
            string[] tvsSymbols = {"ATVI","ADBE", "AKAM", "ALTR", "AMZN", "AMGN", "APOL", "AAPL", "AMAT", "ADSK", "ADP", "BIDU", "BBBY", "BIIB", "BMC", "BRCM", "CHRW", "CA", "CELG", "CEPH", "CERN", "CHKP", "CSCO", "CTXS", "CTSH", "CMCSA", "COST", "CTRP", "DELL", "XRAY", "DTV", "DLTR", "EBAY", "ERTS", "EXPE", "EXPD", "ESRX", "FFIV", "FAST", "FSLR", "FISV", "FLEX", "FLIR", "GRMN", "GENZ", "GILD", "GOOG", "HSIC", "ILMN", "INFY", "INTC", "INTU", "ISRG", "JOYG", "KLAC", "LRCX", "LINTA", "LIFE", "LLTC", "MRVL", "MAT", "MXIM", "MCHP", "MU", "MSFT", "MICC", "MYL", "NTAP", "NFLX", "NWSA", "NIHD", "NVDA", "ORLY", "ORCL", "PCAR", "PAYX", "PCLN", "QGEN", "QCOM", "RIMM", "ROST", "SNDK", "STX", "SHLD", "SIAL", "SPLS", "SBUX", "SRCL", "SYMC", "TEVA", "URBN", "VRSN", "VRTX", "VMED", "VOD", "WCRX", "WFMI", "WYNN", "XLNX", "YHOO"
                                  };
            foreach (string tvsSymbol in tvsSymbols)
            {
                Security tvsItem = new Security();
                tvsItem.Symbol = tvsSymbol;
                ivwNasdaq100WatchList.Securities.Add(tvsItem);
            }
        }
        private void initializeDowWatchlist()
        {
			string [] tvsSymbols = {"AA", "AXP", "BA", "BAC", "CAT", "CSCO", "CVX", "DD", "DIS", "GE", 
				"HD", "HPQ", "IBM", "INTC", "JNJ", "JPM", "KFT", "KO", "MCD", "MMM", "MRK", "MSFT",
				"PFE", "PG", "T", "TRV", "UTX", "VZ", "WMT", "XOM"};
            foreach (string tvsSymbol in tvsSymbols)
            {
                Security tvsItem = new Security();
                tvsItem.Symbol = tvsSymbol;
				ivwDowWatchList.Securities.Add(tvsItem);
            }
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            exitAction();
        }
        private void exitAction()
        {
			PersistSave();
            this.Close();
        }
		private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //the user intention here is to add the item to the existing list of 
            //displayed items. So it is added to the current watchlist (i.e. iviWatchList)
            Security tvsSecurity = new Security();
            tvsSecurity.Symbol = symbolText.Text;
            ivwWatchList.Securities.Add(tvsSecurity);
            UpdateSelection();

            if (!DataTier.IsSymbolValid(tvsSecurity.Symbol))
            {
                WatchList tvwTemp = new WatchList();
                tvwTemp.Securities.Add(tvsSecurity);
                UpdateSelection2(tvwTemp);
            }
        }
        private void calculateDayMatrix()
        {
            ivdDayMatrix.InitializeLists();
            foreach (Security tvsItem in ivwWatchList.Securities)
            {
                //add this items day aggregates to the master list
				
                foreach (DayAggregate tvdDay in tvsItem.DayAggregates)
                {//what is the advantage to the re-loop here? Why not add to matrix on load?
                    ivdDayMatrix.Master.Add(tvdDay);
                }
            }
            if (ivtDayType == DayType.Calendar)
                ivdDayMatrix.CalculateWeekCalendar(ivdSelectionStart, ivdSelectionEnd, ivsSort);
            else if (ivtDayType == DayType.Incremental)
                ivdDayMatrix.CalculateWeekIncremental(ivdSelectionStart, ivsSort);

        }
        private void goAction()
        {            
            tableLayoutPanel1.RowCount = ivdDayMatrix.Monday.Count;

            tableLayoutPanel1.SuspendLayout();
            int tviEnum;
            for (tviEnum = 0; tviEnum < ivdDayMatrix.Monday.Count; tviEnum++)
            {
                DayAggregateControl tvdTempDay;

                tvdTempDay = (DayAggregateControl)tableLayoutPanel1.GetControlFromPosition(0, tviEnum);

                if (tvdTempDay == null)
                {
                    tvdTempDay = new DayAggregateControl();
                    tvdTempDay.Click += new EventHandler(tvdTempDay_Click);                    
                    tvdTempDay.Dock = DockStyle.Fill;
                    tableLayoutPanel1.Controls.Add(tvdTempDay, 0, tviEnum);
                }
                if (tviEnum < ivdDayMatrix.Monday.Count)
                {
                tvdTempDay.DayAggregate = ivdDayMatrix.Monday[tviEnum];

                tvdTempDay = (DayAggregateControl)tableLayoutPanel1.GetControlFromPosition(1, tviEnum);
                }
                if (tvdTempDay == null)
                {
                    tvdTempDay = new DayAggregateControl();
                    tvdTempDay.Click += new EventHandler(tvdTempDay_Click);
                    tvdTempDay.Dock = DockStyle.Fill;
                    tableLayoutPanel1.Controls.Add(tvdTempDay, 1, tviEnum);
                }
                if (tviEnum < ivdDayMatrix.Tuesday.Count)
                {
                    tvdTempDay.DayAggregate = ivdDayMatrix.Tuesday[tviEnum];

                    tvdTempDay = (DayAggregateControl)tableLayoutPanel1.GetControlFromPosition(2, tviEnum);
                }

                if (tvdTempDay == null)
                {
                    tvdTempDay = new DayAggregateControl();
                    tvdTempDay.Click += new EventHandler(tvdTempDay_Click);
                    tvdTempDay.Dock = DockStyle.Fill;
                    tableLayoutPanel1.Controls.Add(tvdTempDay, 2, tviEnum);
                }
                if (tviEnum < ivdDayMatrix.Wednesday.Count)
                {
                    tvdTempDay.DayAggregate = ivdDayMatrix.Wednesday[tviEnum];

                    tvdTempDay = (DayAggregateControl)tableLayoutPanel1.GetControlFromPosition(3, tviEnum);
                }
                if (tvdTempDay == null)
                {
                    tvdTempDay = new DayAggregateControl();
                    tvdTempDay.Click += new EventHandler(tvdTempDay_Click);
                    tvdTempDay.Dock = DockStyle.Fill;
                    tableLayoutPanel1.Controls.Add(tvdTempDay, 3, tviEnum);
                }
                if (tviEnum < ivdDayMatrix.Thursday.Count)
                {
                    tvdTempDay.DayAggregate = ivdDayMatrix.Thursday[tviEnum];

                    tvdTempDay = (DayAggregateControl)tableLayoutPanel1.GetControlFromPosition(4, tviEnum);
                }
                if (tvdTempDay == null)
                {
                    tvdTempDay = new DayAggregateControl();
                    tvdTempDay.Click += new EventHandler(tvdTempDay_Click);
                    tvdTempDay.Dock = DockStyle.Fill;
                    tableLayoutPanel1.Controls.Add(tvdTempDay, 4, tviEnum);
                }
                if (tviEnum < ivdDayMatrix.Friday.Count)
                {
                    tvdTempDay.DayAggregate = ivdDayMatrix.Friday[tviEnum];
                }             
            }

            while((tviEnum*5) < tableLayoutPanel1.Controls.Count)
            {
                tableLayoutPanel1.Controls.RemoveAt((tviEnum * 5));
            }
            
            tableLayoutPanel1.ResumeLayout();
            tableLayoutPanel1.Invalidate(true);
        }

       
        void tvdTempDay_Click(object sender, EventArgs e)
        {
            DayAggregateControl tvControl = (DayAggregateControl)sender;            
            setAllProperties(tvControl.DayAggregate);

            tvControl.Focus();
            if (ivdPriorControl!=null)
            ivdPriorControl.Invalidate();
            tvControl.Invalidate();
            ivdPriorControl = tvControl;
        }

        private void updateTree()
		{
			TreeNode [] tvNodes = treeView1.Nodes.Find("Recent", true);
			tvNodes[0].Nodes.Clear();
			foreach (Security tvsItem in ivwWatchList.Securities)
            {
                tvNodes[0].Nodes.Add(tvsItem.Symbol, tvsItem.Symbol,"star.png", "star.png");
			}
			
		}        
        void tvYahoo_DownloadPricesCompleted(object sender, EventArgs e)
        {
			YahooDataDownloader tvDL = (YahooDataDownloader)sender;
            tvDL.Security.LastDownloadTime = DateTime.Now;
            SecurityInit(tvDL.Security);			
        }
        private void SecurityInit(Security fvsSecurity)        
        {
            fvsSecurity.Calculate(ivdSelectionStart, ivdSelectionEnd);
        }        
		private void treeview1_AfterSelect(object sender, /*TreeViewCancel*/EventArgs e)
		{

            TreeNode tvNode = treeView1.SelectedNode;
			
			if (tvNode == null)
				return;
            if (tvNode.IsEditing)
                return;
			
            if (tvNode.Text == "Dow")
            {
                ivwWatchList = ivwDowWatchList;
                UpdateSelection();
               
                return;
            }
            if (tvNode.Text == "Nasdaq 100")
            {
                ivwWatchList = ivwNasdaq100WatchList;
                UpdateSelection();
                return;
            }
			if ((tvNode.Text == "Recent") ||
			    (tvNode.Text == "Indexes") ||
			    (tvNode.Text == "Custom"))
				return;
            else if ((string)tvNode.Tag == "Watchlist")
            {
                ivwWatchList = new WatchList();
                ivwWatchList.Type = WatchListType.Basic;

                foreach (TreeNode tvNodee in tvNode.Nodes)
                {
                    Security tvsItem = new Security();
                    tvsItem.Symbol = tvNodee.Text;
                    ivwWatchList.Securities.Add(tvsItem);
                }
                UpdateSelection();
                
            }
            else
			{
                ivwWatchList = new WatchList();
                ivwWatchList.Type = WatchListType.Basic;
                
                Security tvsItem = new Security();
                tvsItem.Symbol = tvNode.Text;
                ivwWatchList.Securities.Add(tvsItem);                
                symbolText.Text = tvNode.Text;
                UpdateSelection();
			}
		}
        private void MainForm_Load(object sender, EventArgs e)        
        {            
			securityEntry = new SecurityEntry();
			treeView1.Nodes.Add("Recent", "Recent", "clock.png","clock.png");
           
            treeView1.Nodes.Add("Index", "Indexes", "text_list_numbers.png", "text_list_numbers.png");
            TreeNode tvNode = treeView1.Nodes.Add("Custom", "Custom", "folder_edit.png", "folder_edit.png");
            tvNode.ContextMenuStrip = this.addWatchlistOrSymbolMenuStrip2;

            dateTimePicker1.Value = DateTime.Now.AddDays(DayOfWeek.Sunday - DateTime.Now.DayOfWeek);

            PersistLoad();            
            loadIndexNodes();
		}
		private void DoSomeWork(object sender, DoWorkEventArgs e)
        {
			BackgroundWorker bw = sender as BackgroundWorker;
			
			WatchList fvwWatchlist = (WatchList)e.Argument;

			//trying to do 7 things at once.
			//1. if we have the item, what is the last updated day? Download from then to now.
			//2. if we do not have the item, donwload from 1950 to now.
			
			int i=0;//hack
			foreach (Security tvsItem in fvwWatchlist.Securities)
            {
				if(bw.CancellationPending) 
				{
					e.Cancel = true;
					break;
				}
				
				//check if have history
				tvsItem.persistLoad2();
				//use lasdownloadtime and try again.
				DoSpecificDownload(tvsItem);
				
				int pc = i*100/fvwWatchlist.Securities.Count;				
				bw.ReportProgress(pc);				
				i++;
			}
        }
		private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			toolStripStatusLabel2.Text = "Downloading";
			progressBar1.Visible=true;
			progressBar1.Value = e.ProgressPercentage;			
		}
		private void bw_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
		{
			if (!e.Cancelled)
			{
				//calculateDayMatrix();
				ivdDayMatrix.InitializeLists();
				BuildQuery();
	            goAction();
	            updateTree();
	            calculateLabels();
			}
			progressBar1.Maximum=100;
			progressBar1.Minimum=0;
			progressBar1.Value=0;
			progressBar1.Visible=false;
			toolStripStatusLabel2.Text = "Ready";
		}
        private void resetWindowLocations()
        {
			splitter2.Panel2Collapsed=false;
			splitter3.Panel1Collapsed=false;
			splitter3.Panel2Collapsed=false;
            splitter1.Panel1Collapsed = false;

			detailsWindowToolStripMenuItem.Checked=true;
			historyWindowToolStripMenuItem.Checked=true;
			watchlistExplorerToolStripMenuItem.Checked=true;
			
        }
        private void loadIndexNodes()
        {
            treeView1.Nodes["Index"].Nodes.Add("Dow", "Dow", "tag_blue.png", "tag_blue.png");
            treeView1.Nodes["Index"].Nodes.Add("Nasdaq 100", "Nasdaq 100", "tag_blue.png", "tag_blue.png");
        }
		public static FileInfo ItemsFile
        {
            get 
            {
                return new FileInfo(Path.Combine(Application.StartupPath, "securities.xml"));
            }
        }
        public static FileInfo WatchlistsFile
        {
            get
            {
                return new FileInfo(Path.Combine(Application.StartupPath, "watchlists.xml"));
            }
        }
		public void PersistLoad()
		{
            //need to reset the watchlist to be the recent items?
			if (ItemsFile.Exists)
            {
				List<string> tvsSymbols = new List<string>();
				
                XmlSerializer xml = new XmlSerializer(tvsSymbols.GetType());

				
                using (Stream s = ItemsFile.OpenRead())
                {
					tvsSymbols = xml.Deserialize(s) as List<string>;
                }
				ivwRecentWatchList.Securities.Clear();
				foreach(string tvsSymbol in tvsSymbols)
				{
					Security tvsSecurity = new Security();
					tvsSecurity.Symbol = tvsSymbol;
                    ivwRecentWatchList.Securities.Add(tvsSecurity);
				}
                //ivwWatchList = ivwRecentWatchList;
			}
            if (WatchlistsFile.Exists)
            {
                List<List<string>> tvsWatchLists = new List<List<string>>();
                XmlSerializer xml = new XmlSerializer(tvsWatchLists.GetType());


                using (Stream s = WatchlistsFile.OpenRead())
                {
                    tvsWatchLists = xml.Deserialize(s) as List<List<string>>;
                }
                TreeNode tvCustom = treeView1.Nodes["Custom"];
                tvCustom.Nodes.Clear();

                foreach (List<string>tvsWatchlist in tvsWatchLists)
                {
                    TreeNode tvWLNode = tvCustom.Nodes.Add("Watchlist", tvsWatchlist[0], "folder_star.png", "folder_star.png");
                    tvWLNode.Tag = "Watchlist";

                    foreach (string tvsWLItem in tvsWatchlist)
                    {
                        if (tvsWLItem == tvWLNode.Text)
                            continue;
                        if (tvsWLItem.Length == 0)
                            continue;

                        tvWLNode.Nodes.Add(tvsWLItem.ToUpper(CultureInfo.CurrentCulture), tvsWLItem.ToUpper(CultureInfo.CurrentCulture), "star.png", "star.png");
                    }
                }
            }
		}
		public void PersistSave()
		{
			List<string> tvsSymbols = new List<string>();
			foreach(Security tvsSecurity in ivwWatchList.Securities)
			{
				tvsSymbols.Add(tvsSecurity.Symbol);
			}
			XmlSerializer xmls = new XmlSerializer(tvsSymbols.GetType());

            if (ItemsFile.Exists)
            {
                ItemsFile.Delete();
            }

            using (Stream s = ItemsFile.OpenWrite())
            {
                xmls.Serialize(s, tvsSymbols);
                s.Close();
            }

            List<List<string>> tvsWatchLists = new List<List<string>>();
            //get all the nodes under "Custom" from the treeview
            TreeNode tvCustom = treeView1.Nodes["Custom"];
            foreach (TreeNode tvWatchList in tvCustom.Nodes)
            {
                List<string> tvsWLSecurities = new List<string>();
                tvsWLSecurities.Add(tvWatchList.Text);//quirk...1st item is actually WL name.
                foreach (TreeNode tvnSecurity in tvWatchList.Nodes)
                {
                    if (tvnSecurity.Text.Length == 0)
                        continue;

                    tvsWLSecurities.Add(tvnSecurity.Text);
                }
                tvsWatchLists.Add(tvsWLSecurities);
            }

            XmlSerializer tvxSerializer = new XmlSerializer(tvsWatchLists.GetType());

            if (WatchlistsFile.Exists)
            {
                WatchlistsFile.Delete();
            }

            using (Stream s = WatchlistsFile.OpenWrite())
            {
                tvxSerializer.Serialize(s, tvsWatchLists);
                s.Close();
            }
		}

       
        private void setAllProperties(DayAggregate fvsDayAggregate)
        {
            fillDetails(fvsDayAggregate);
            fillPrices(fvsDayAggregate);
            performanceChart.Invalidate();
            priceChart.Invalidate();
        }
        private void fillDetails(DayAggregate fvsDayAggregate)
        {
			pgDetails.SelectedObject = fvsDayAggregate;
        }
        private void fillPrices(DayAggregate fvsDayAggregate)
        {
            ivlvPrices.SuspendLayout();
            ivlvPrices.Items.Clear();
            foreach (HistoricalPrice tvhPrice in fvsDayAggregate.HistoricalPrices)
            {
                    DateTime dtDate = new DateTime(tvhPrice.Year, tvhPrice.Month, tvhPrice.Day);
                    ListViewItem tvlwItem = new ListViewItem(new string[] {
            dtDate.ToShortDateString(),
            tvhPrice.OpenPrice.ToString(CultureInfo.CurrentCulture),
            tvhPrice.HighPrice.ToString(CultureInfo.CurrentCulture),
            tvhPrice.LowPrice.ToString(CultureInfo.CurrentCulture),
            tvhPrice.ClosePrice.ToString(CultureInfo.CurrentCulture),
            tvhPrice.GainPriorClose.ToString(CultureInfo.CurrentCulture),//need to add this member (gain/gain%) to object
            tvhPrice.GainPriorClosePercent.ToString(CultureInfo.CurrentCulture),
            tvhPrice.Volume.ToString(CultureInfo.CurrentCulture)});
                    tvlwItem.BackColor = calculateRowColor(tvhPrice.GainPriorClosePercent);
                    int avg = (tvlwItem.BackColor.R + tvlwItem.BackColor.G + tvlwItem.BackColor.B) / 3;

                    if (avg > 255 / 2)
                    {
                        tvlwItem.ForeColor = Color.Black;
                    }
                    else
                    {
                        tvlwItem.ForeColor = Color.White;
                    }

                    ivlvPrices.Items.Add(tvlwItem);                
            }
            ivlvPrices.ResumeLayout(false);
            ivlvPrices.PerformLayout();
        }
        private static Color calculateRowColor(decimal fvdGainPercent)
        {
            Color tvcReturn = Color.White;
            if (fvdGainPercent > Convert.ToDecimal(2.50))
                tvcReturn = Color.GreenYellow;
            else if (fvdGainPercent > Convert.ToDecimal(2.0))
                tvcReturn = Color.Green;
            else if (fvdGainPercent > 0)
                tvcReturn = Color.DarkGreen;
            else if (fvdGainPercent < Convert.ToDecimal(-2.5))
                tvcReturn = Color.Red;
            else if (fvdGainPercent < Convert.ToDecimal(-2))
                tvcReturn = Color.OrangeRed;
            else if (fvdGainPercent < Convert.ToDecimal(0))
                tvcReturn = Color.Orange;
            return tvcReturn;
        }

        private void performanceChart_Paint(object sender, PaintEventArgs e)
        {
            performanceChartPaintBackground(e);
            Size tvsSize = new Size(0, 0);

            if (ivlvPrices.Items.Count>0)
                tvsSize = performanceChartPaintItems(e);

            performanceChartPaintAxes(e,tvsSize);

        }
        private static void performanceChartPaintBackground(PaintEventArgs e)
        {
            e.Graphics.FillRectangle(new LinearGradientBrush(e.ClipRectangle, Color.White, Color.SkyBlue, -90), e.ClipRectangle);
            Rectangle tvrRect = e.ClipRectangle;
            tvrRect.Inflate(-20, -20);
            
            e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(85, Color.White)), tvrRect);
        }
        private static void performanceChartPaintAxes(PaintEventArgs e, Size fvsSize)
        {
            Rectangle tvrDrawArea = e.ClipRectangle;
            e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Black)), tvrDrawArea.Left + 60, tvrDrawArea.Top + 45, tvrDrawArea.Left + 60, tvrDrawArea.Bottom - 45);
            e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Black)), tvrDrawArea.Left + 60, (tvrDrawArea.Height - 15) / 2, tvrDrawArea.Right - 30, (tvrDrawArea.Height - 15) / 2);

            // need to draw axis labels
            e.Graphics.DrawString(fvsSize.Width.ToString(CultureInfo.CurrentCulture) + "%", SystemFonts.DefaultFont, SystemBrushes.WindowText, 20, 45);
            e.Graphics.DrawString("-" + fvsSize.Width.ToString(CultureInfo.CurrentCulture)  +"%", SystemFonts.DefaultFont, SystemBrushes.WindowText, 20, e.ClipRectangle.Height - 45 - SystemFonts.DefaultFont.Height);
        }
        private Size performanceChartPaintItems(PaintEventArgs e)
        {
            int tviHorizontalSpace = 0;
            tviHorizontalSpace = e.ClipRectangle.Width - 60 - 30;
            int tviLeftOffset = 60;
            int tviSpacePerBar = Math.Max((tviHorizontalSpace/ivlvPrices.Items.Count),1);

            int tviBarZone = Math.Max((tviSpacePerBar / 3),1);

            Size tviMaxMinValues = performanceChartCalculateMaxMin(ivlvPrices.Items);

            decimal tvdMultiplier = (((Convert.ToDecimal(e.ClipRectangle.Height) - 90) / 2) / Math.Max((tviMaxMinValues.Width-tviMaxMinValues.Height),1));
            
            

            for (int i = (ivlvPrices.Items.Count-1); i>-1; i--)
            {
                ListViewItem tvItem = ivlvPrices.Items[i];
                Rectangle tvrTemp = performanceChartCalculateBarSize(tvItem, tviLeftOffset + tviBarZone, tviBarZone, (e.ClipRectangle.Height - 15) / 2, tvdMultiplier);
                if (tvrTemp.Y < ((e.ClipRectangle.Height - 15) / 2))
                e.Graphics.FillRectangle(new LinearGradientBrush(tvrTemp, Color.FromArgb(15, 170, 29), Color.FromArgb(6, 8, 6), 16), tvrTemp);
                else
                    e.Graphics.FillRectangle(new LinearGradientBrush(tvrTemp, Color.FromArgb(6, 8, 6), Color.FromArgb(15, 170, 29), 16), tvrTemp);
                tviLeftOffset += tviSpacePerBar;


            }

            return tviMaxMinValues;
        }
        private static Rectangle performanceChartCalculateBarSize(ListViewItem fvlItem, int fviLeft, int fviWidth, int fviYAxisMidPoint, decimal fviUnitMultiplier)
        {
            Rectangle tvrTemp = new Rectangle();
            tvrTemp.X = fviLeft;
            tvrTemp.Width = fviWidth;
            int tviBarHeight = Convert.ToInt32(Convert.ToDecimal(fvlItem.SubItems[6].Text, CultureInfo.CurrentCulture) * fviUnitMultiplier);
            tvrTemp.Width = Math.Max(Math.Abs(fviWidth), 1);
            tvrTemp.Height = Math.Max(Math.Abs(tviBarHeight), 1);
            if (tviBarHeight >= 0)
                tvrTemp.Y = fviYAxisMidPoint - tviBarHeight;
            else if (tviBarHeight<0)
                tvrTemp.Y = fviYAxisMidPoint;

            return tvrTemp;
        }
        private static Size performanceChartCalculateMaxMin(ListView.ListViewItemCollection fvlwItems)
        {
            Size tvsSize = new Size(1, 1);
            foreach (ListViewItem tvItem in fvlwItems)
            {
                int tviPrice = Math.Abs(Convert.ToInt32(Convert.ToDecimal(tvItem.SubItems[6].Text, CultureInfo.CurrentCulture)));
                if (tviPrice > tvsSize.Width)
                    tvsSize.Width = tviPrice;
                if (tviPrice < tvsSize.Height)
                    tvsSize.Height = tviPrice;
            }
            return tvsSize;
        }
        private static Size priceChartCalculateMaxMin(ListView.ListViewItemCollection fvlwItems)
        {
            Size tvsSize = new Size(1, 999999999);
            foreach (ListViewItem tvItem in fvlwItems)
            {
                int tviPrice = Math.Abs(Convert.ToInt32(Convert.ToDecimal(tvItem.SubItems[2].Text, CultureInfo.CurrentCulture)));
                if (tviPrice > tvsSize.Width)
                    tvsSize.Width = tviPrice;
                tviPrice = Math.Abs(Convert.ToInt32(Convert.ToDecimal(tvItem.SubItems[3].Text, CultureInfo.CurrentCulture)));
                if (tviPrice < tvsSize.Height)
                    tvsSize.Height = tviPrice;
            }
            return tvsSize;
        }


        private void ivlvPrices_SizeChanged(object sender, EventArgs e)
        {
            ListView tvlwItem = (ListView)sender;
            int tviEachColumnWidth = tvlwItem.Width/tvlwItem.Columns.Count;
            
            foreach (ColumnHeader tvCol in tvlwItem.Columns)
            {
                tvCol.Width = tviEachColumnWidth;
            }
        }

        private void priceChart_Paint(object sender, PaintEventArgs e)
        {
            performanceChartPaintBackground(e);

            Size tvsSize = new Size(0, 0);

            if (ivlvPrices.Items.Count > 0)
                tvsSize = priceChartPaintItems(e);

            priceChartPaintAxes(e, tvsSize);
        }

        private Size priceChartPaintItems(PaintEventArgs e)
        {
            int tviHorizontalSpace = 0;
            tviHorizontalSpace = e.ClipRectangle.Width - 60 - 30;
            int tviLeftOffset = 60;
            int tviSpacePerBar = tviHorizontalSpace / ivlvPrices.Items.Count;

            int tviBarZone = tviSpacePerBar / 3;

            Size tviMaxMinValues = priceChartCalculateMaxMin(ivlvPrices.Items);

            decimal tvdMultiplier = (((Convert.ToDecimal(e.ClipRectangle.Bottom) - 90) ) / (tviMaxMinValues.Width - tviMaxMinValues.Height));



            for (int i = (ivlvPrices.Items.Count - 1); i > -1; i--)//ListViewItem tvItem in ivlvPrices.Items)
            {
                ListViewItem tvItem = ivlvPrices.Items[i];
                Rectangle tvrTemp = priceChartCalculateBarSize(tvItem, tviLeftOffset + tviBarZone, /*tviBarZone*/2, (e.ClipRectangle.Bottom-30+tviMaxMinValues.Height), tvdMultiplier);

                e.Graphics.FillRectangle(new SolidBrush(Color.Black), tvrTemp);
                tviLeftOffset += tviSpacePerBar;
            }

            return tviMaxMinValues;
        }
        private static Rectangle priceChartCalculateBarSize(ListViewItem fvlItem, int fviLeft, int fviWidth, int fviYAxisMidPoint, decimal fviUnitMultiplier)
        {
            Rectangle tvrTemp = new Rectangle();
            tvrTemp.X = fviLeft;
            tvrTemp.Width = fviWidth;
            int tviBarHeight = Convert.ToInt32((Convert.ToDecimal(fvlItem.SubItems[2].Text, CultureInfo.CurrentCulture) - Convert.ToDecimal(fvlItem.SubItems[3].Text, CultureInfo.CurrentCulture)) * fviUnitMultiplier);
            tvrTemp.Height = Math.Max(Math.Abs(tviBarHeight), 1);
            tvrTemp.Y = fviYAxisMidPoint - Convert.ToInt32(Convert.ToDecimal(fvlItem.SubItems[2].Text, CultureInfo.CurrentCulture) * fviUnitMultiplier);

            return tvrTemp;
        }
        private static void priceChartPaintAxes(PaintEventArgs e, Size fvsSize)
        {
            Rectangle tvrDrawArea = e.ClipRectangle;
            e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Black)), tvrDrawArea.Left + 60, tvrDrawArea.Top + 45, tvrDrawArea.Left + 60, tvrDrawArea.Bottom - 45);
            e.Graphics.DrawLine(new Pen(new SolidBrush(Color.Black)), tvrDrawArea.Left + 60, tvrDrawArea.Bottom-45, tvrDrawArea.Right - 30, tvrDrawArea.Bottom-45);

            // need to draw axis labels
            e.Graphics.DrawString(fvsSize.Width.ToString(CultureInfo.CurrentCulture), SystemFonts.DefaultFont, SystemBrushes.WindowText, 20, 45);
            e.Graphics.DrawString(fvsSize.Height.ToString(CultureInfo.CurrentCulture), SystemFonts.DefaultFont, SystemBrushes.WindowText, 20, e.ClipRectangle.Height - 45 - SystemFonts.DefaultFont.Height);
        }

        private void probabilityToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string tvsTitle = "Fincal Report: Probability\nCopyright 2010 Fincal.com";
            string tvsDescription = "This report displays the selected securities sorted by their historic probability of rising. The securities included in this report are: ";
            string tvsData = "";
			
			tvsData = DataTier.GetReportProbability(tvsData, GetSymbolList());
            showReport(tvsTitle, tvsDescription, tvsData);		
        }
        private static void showReport(string fvsTitle, string fvsDescription, string fvsData)
        {
            Reports tvReports = new Reports();
            tvReports.setReportText(fvsTitle + "\n\n" + fvsDescription + "\n\n" + fvsData);
            tvReports.ShowDialog();
        }

        private void gainPercentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string tvsTitle = "Fincal Report: Probability\nCopyright 2010 Fincal.com";
            string tvsDescription = "This report displays the selected securities sorted by their historic probability of rising. The securities included in this report are: ";
            string tvsData = "Symbol\tMonth/Day\tAvg. Gain (%)\tCount\r\n";
            tvsData += "======\t=========\t=============\t======\r\n\r\n";
            tvsData = DataTier.GetReportGainPercent(tvsData, GetSymbolList());
            showReport(tvsTitle, tvsDescription, tvsData);		
        }
        
        private void gainToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string tvsTitle = "Fincal Report: Average Gain\nCopyright 2010 Fincal.com";
            string tvsDescription = "This report displays the selected securities sorted by their historic probability of rising. The securities included in this report are: ";
            string tvsData = "Symbol\tCount\tRise\tGain\tDay/Month\r\n";
            tvsData += "======\t======\t====\t====\t=========\r\n\r\n";
            tvsData = DataTier.GetReportGain(tvsData, GetSymbolList());
            showReport(tvsTitle, tvsDescription, tvsData);
        }
        

        private void next3DaysToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string tvsTitle = "Fincal Report: Predictive: Next 3 Days\nCopyright 2010 Fincal.com";
            string tvsDescription = "This report displays the selected securities sorted by their historic probability of rising. The securities included in this report are: ";
            string tvsData = "Symbol\tMonth/Day\tAvg. Gain (%)\tCount\r\n";
            tvsData += "======\t=========\t=============\t======\r\n\r\n";
            tvsData = DataTier.GetReport3Days(tvsData, GetSymbolList());
            showReport(tvsTitle, tvsDescription, tvsData);
        }

        private void next5DaysToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //easy refactor
            string tvsTitle = "Fincal Report: Predictive: Next 3 Days\nCopyright 2010 Fincal.com";
            string tvsDescription = "This report displays the selected securities sorted by their historic probability of rising. The securities included in this report are: ";
            string tvsData = "Symbol\tMonth/Day\tAvg. Gain (%)\tCount\r\n";
            tvsData += "======\t=========\t=============\t======\r\n\r\n";
            tvsData = DataTier.GetReportGain(tvsData, GetSymbolList());
            showReport(tvsTitle, tvsDescription, tvsData);
        }

        private void nextMonthToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //easy refactor
            string tvsTitle = "Fincal Report: Predictive: Next 3 Days\nCopyright 2010 Fincal.com";
            string tvsDescription = "This report displays the selected securities sorted by their historic probability of rising. The securities included in this report are: ";
            string tvsData = "Symbol\tMonth/Day\tAvg. Gain (%)\tCount\r\n";
            tvsData += "======\t=========\t=============\t======\r\n\r\n";
            tvsData = DataTier.GetReportGain(tvsData, GetSymbolList());
            showReport(tvsTitle, tvsDescription, tvsData);
        }

        

        private void next3MonthsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //easy refactor
            string tvsTitle = "Fincal Report: Predictive: Next 3 Days\nCopyright 2010 Fincal.com";
            string tvsDescription = "This report displays the selected securities sorted by their historic probability of rising. The securities included in this report are: ";
            string tvsData = "Symbol\tMonth/Day\tAvg. Gain (%)\tCount\r\n";
            tvsData += "======\t=========\t=============\t======\r\n\r\n";
            tvsData = DataTier.GetReportGain(tvsData, GetSymbolList());
            showReport(tvsTitle, tvsDescription, tvsData);
        }

        private void probabilityVsGainPercentToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

      

        

        private void addStripMenuItem1_Click(object sender, EventArgs e)
        {
            TreeNode tvSelected = treeView1.SelectedNode;
            if (tvSelected == null)
                return;
            if (tvSelected == treeView1.Nodes["Custom"])
            {
                WatchlistEntry tvwWatchlist = new WatchlistEntry();
                tvwWatchlist.ShowDialog();
                addTreeItem(tvwWatchlist.textBox1.Text, true);
            }
            else
            {
                securityEntry.ShowDialog();
                addTreeItem(securityEntry.textBox1.Text, false);
            }
        }
        private void addTreeItem(string Symbols, bool IsWatchlist)
        {
			
			TreeNode tvSelected = treeView1.SelectedNode;
			if (tvSelected==null)
				return;
            if (Symbols.Length == 0)
                return;

            if (IsWatchlist)
            {
                TreeNode tvAdd = new TreeNode();

                string tvsImage = "folder_star.png";

                tvAdd.Tag = "Watchlist";
                tvAdd.Text = Symbols;
                tvAdd.ImageKey = tvsImage;
                tvAdd.SelectedImageKey = tvsImage;

                tvSelected.Nodes.Add(tvAdd);
            }
            else
            {
                string[] tvsSymbols = Symbols.Split(new char[] { ' ' });
				WatchList tvwTemp = new WatchList();
                foreach (string tvsSymbol in tvsSymbols)
                {
                    if (tvsSymbol.Length == 0)
                        continue;
                    TreeNode tvAdd = new TreeNode();

                    string tvsImage = "star.png";
                    tvAdd.Text = tvsSymbol.ToUpper(CultureInfo.CurrentCulture);
                    tvAdd.ImageKey = tvsImage;
                    tvAdd.SelectedImageKey = tvsImage;
                    tvSelected.Nodes.Add(tvAdd);
					Security tvsItem = new Security();
					tvsItem.Symbol = tvAdd.Text;
					tvwTemp.Securities.Add(tvsItem);
                }
				UpdateSelection2(tvwTemp);
            }
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            ivdSelectionStart = dateTimePicker1.Value.AddDays(DayOfWeek.Sunday - dateTimePicker1.Value.DayOfWeek);
            ivdSelectionEnd = dateTimePicker1.Value.AddDays(DayOfWeek.Saturday - dateTimePicker1.Value.DayOfWeek);
			UpdateSelection();
        }
        private void calculateLabels()
        {
            DateTime tvdDay = ivdSelectionStart.AddDays(1);
            lblMonday.Text = tvdDay.ToString("dddd", CultureInfo.CurrentCulture) + " " + tvdDay.ToString("dd", CultureInfo.CurrentCulture);

            tvdDay = tvdDay.AddDays(1);
            lblTuesday.Text = tvdDay.ToString("dddd", CultureInfo.CurrentCulture) + " " + tvdDay.ToString("dd", CultureInfo.CurrentCulture);

            tvdDay = tvdDay.AddDays(1);
            lblWednesday.Text = tvdDay.ToString("dddd", CultureInfo.CurrentCulture) + " " + tvdDay.ToString("dd", CultureInfo.CurrentCulture);

            tvdDay = tvdDay.AddDays(1);
            lblThursday.Text = tvdDay.ToString("dddd", CultureInfo.CurrentCulture) + " " + tvdDay.ToString("dd", CultureInfo.CurrentCulture);

            tvdDay = tvdDay.AddDays(1);
            lblFriday.Text = tvdDay.ToString("dddd", CultureInfo.CurrentCulture) + " " + tvdDay.ToString("dd", CultureInfo.CurrentCulture);

        }

        private void tsLessSelection_Click(object sender, EventArgs e)
        {
            dateTimePicker1.Value = ivdSelectionStart.AddDays(-7);
        }

        private void tsMoreSelection_Click(object sender, EventArgs e)
        {
            dateTimePicker1.Value = ivdSelectionStart.AddDays(7);
        }

        private void lblDayColumnHeader_Paint(object sender, PaintEventArgs e)
        {
            Label tvlLabel = (Label)sender;
            
            Color shineColor = Color.SkyBlue;
            TableLayoutPanel tvtParent = (TableLayoutPanel)tvlLabel.Parent;
            if ((ivdSelectionStart.CompareTo(DateTime.Now) <= 0) && (ivdSelectionEnd.CompareTo(DateTime.Now) >= 0))
            {
                if (tvtParent.GetCellPosition(tvlLabel).Column == (int)(DateTime.Now.DayOfWeek - 1))
                    shineColor = Color.Orange;
            }

            Color c1 = ControlPaint.Light(shineColor);
            Color c2 = ControlPaint.LightLight(shineColor);

            Rectangle tvrArea = new Rectangle(0, 0, tvlLabel.Width, tvlLabel.Height);

            GradientHelper.GlossyRect(e.Graphics, tvrArea, c2, c1, shineColor, c1);
            e.Graphics.DrawString(tvlLabel.Text, SystemFonts.DefaultFont, Brushes.Black, new PointF(4, 4));
            tvrArea.Height--;
            e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.Gray)), tvrArea);
            
        }

        private void calendarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ivtDayType = DayType.Calendar;			
            calculateDayMatrix();
            goAction();            
        }

        private void incrementalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ivtDayType = DayType.Incremental;
            calculateDayMatrix();
            goAction();            
        }

        private void tableLayoutPanel1_Resize(object sender, EventArgs e)
        {
            //tableLayoutPanel1.SuspendLayout();            
            
            /*for (int tviEnum = 0; tviEnum < 5; tviEnum++)
            {
                tableLayoutPanel2.Controls[tviEnum].Width = tableLayoutPanel2.Controls[tviEnum].Width;
            }*/
            //tableLayoutPanel2.Controls[4].Width += 22;
			Control tvcControl = (Control)sender;
			tableLayoutPanel1.Location = new System.Drawing.Point(0,0);
			tableLayoutPanel1.Size = new Size(tvcControl.Width, tableLayoutPanel1.Height);
			
           
            if (ivdPriorControl != null)
            {
                ivdPriorControl.Focus();
                //ivdPriorControl.Invalidate();
            }
            //tableLayoutPanel1.Invalidate();
            //tableLayoutPanel1.ResumeLayout(false);
            //tableLayoutPanel1.PerformLayout();
        }

        private void symbolToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //need to check of asc/desc is selected.
            ivsSort = SecuritySort.AlphaAZ;
            ivdDayMatrix.SortDays(DayAggregateSorter.SortAggregatesBySymbol);
            goAction();
        }

        private void riseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ivsSort = SecuritySort.RiseDown;
            ivdDayMatrix.SortDays(DayAggregateSorter.SortAggregatesByProbability);
            goAction();
        }

        private void AverageGainToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ivsSort = SecuritySort.AverageGainPCDownPriorClose;
            ivdDayMatrix.SortDays(DayAggregateSorter.SortAggregatesByGainPercentPriorClose);
            goAction();
        }

        private void medianToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ivsSort = SecuritySort.MedianGainPCDown;
            ivdDayMatrix.SortDays(DayAggregateSorter.SortAggregatesByMedianPercent);
            goAction();
        }
		
		private void deltaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ivsSort = SecuritySort.DeltaGainDown;
            ivdDayMatrix.SortDays(DayAggregateSorter.SortAggregatesByStdDeviationGainPercentDelta);
            goAction();
        }

        private void newWatchlistToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeView1.SelectedNode = treeView1.Nodes["Custom"];
            //addTreeItem();
            WatchlistEntry tvwWatchlist = new WatchlistEntry();
            tvwWatchlist.ShowDialog();
            addTreeItem(tvwWatchlist.textBox1.Text, true);
            PersistSave();
        }

        private void newSecuritToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //addTreeItem();
			securityEntry.ShowDialog();
			addTreeItem(securityEntry.textBox1.Text, false);
            PersistSave();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PersistSave();
        }

        private void resetWindowLocationsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            resetWindowLocations();
        }        
		private void historyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toggleHistorywindow();            
		}

		private void toggleHistorywindow()
		{
			splitter2.Panel2Collapsed = !splitter2.Panel2Collapsed;
			historyWindowToolStripMenuItem.Checked = !splitter2.Panel2Collapsed;
		}
		private void detailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toggleDetailswindow();
            checkMainSplitter();
		}

		private void toggleDetailswindow()
		{
            detailsWindowToolStripMenuItem.Checked = !detailsWindowToolStripMenuItem.Checked;
		}
        private void checkMainSplitter()
        {
            if ((detailsWindowToolStripMenuItem.Checked) || (watchlistExplorerToolStripMenuItem.Checked))
                splitter1.Panel1Collapsed = false;
            if ((!detailsWindowToolStripMenuItem.Checked) && (!watchlistExplorerToolStripMenuItem.Checked))
                splitter1.Panel1Collapsed = true;
            splitter3.Panel1Collapsed = !watchlistExplorerToolStripMenuItem.Checked;
            splitter3.Panel2Collapsed = !detailsWindowToolStripMenuItem.Checked;
        }
		private void watchlistToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toggleWatchlistwindow();
            checkMainSplitter();
		}

		private void toggleWatchlistwindow()
		{
            watchlistExplorerToolStripMenuItem.Checked = !watchlistExplorerToolStripMenuItem.Checked; 
		}
		
		private void UpdateSelection()
		{
			this.Cursor = Cursors.WaitCursor;
			Application.DoEvents();
			ivdDayMatrix.InitializeLists();
			BuildQuery();
			if (ivdDayMatrix.Master.Count>0)
			{
            	goAction();
            	calculateLabels();
			}
			this.Cursor = Cursors.Default;
			Application.DoEvents();
		}
        private void UpdateSelection2(WatchList TemporaryWatchlist)
        {			
			progressBar1.Maximum=100;
			progressBar1.Minimum=0;
			progressBar1.Value=0;
            toolStripStatusLabel2.Text = "Downloading ";
            
            progressBar1.Visible = true;
            Application.DoEvents();
			
			BackgroundWorker bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
			bw.WorkerReportsProgress=true;
			bw.DoWork+=new DoWorkEventHandler(DoSomeWork);
			bw.ProgressChanged+=new ProgressChangedEventHandler(bw_ProgressChanged);
			bw.RunWorkerCompleted+=new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
			
			bw.RunWorkerAsync(TemporaryWatchlist);
        }

        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int tviLevel = Convert.ToInt32(toolStripComboBox1.Text.Substring(0, toolStripComboBox1.Text.Length - 1));
            zoomTable(tviLevel);
        }
        private void zoomTable(int ZoomLevel)
        {
            float scaleLevel = ZoomLevel / 100f;

            tableLayoutPanel1.SuspendLayout();
            
            tableLayoutPanel1.Scale(new SizeF(1, 1));
            tableLayoutPanel1.Scale(new SizeF(scaleLevel, scaleLevel));
            tableLayoutPanel1.ResumeLayout(false);
            tableLayoutPanel1.PerformLayout();
        }

        private void probabilityVsGainToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {
			Control tvcControl = (Control)sender;
            Color shineColor = Color.SkyBlue;

            Color c2 = ControlPaint.LightLight(shineColor);

            Rectangle tvrArea = new Rectangle(0, 0, tvcControl.Width, tvcControl.Height);

            GradientHelper.GradientRect(e.Graphics, tvrArea, shineColor, c2);
        }
        void toolStripTextBox1_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolStripButton1.PerformClick();
                e.Handled = true;
            }
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {
            Panel pSource = (Panel)sender;
			Color shineColor = SystemColors.ButtonFace;
            
            Color c2 = ControlPaint.LightLight(shineColor);

            Rectangle tvrArea = new Rectangle(0, 0, pSource.Width, pSource.Height);
			GradientHelper.GradientRect(e.Graphics, tvrArea, c2, shineColor);
        }
		private void refreshInvokeToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Refresh();
		}
		private void Refresh()
		{
			UpdateSelection2(ivwWatchList); //?
		}
		private void helpInvokeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowHelp();
		}
		private void ShowHelp()
		{
			// show the pdf.
			System.Diagnostics.Process.Start(Path.Combine(Application.StartupPath, "Documentation.pdf"));
		}
		private void donateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toggleWatchlistwindow();
            checkMainSplitter();
		}
		private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toggleWatchlistwindow();
            checkMainSplitter();
		}
		public void DoSpecificDownload(Security tvsItem)
		{
			tvsItem.PriceDownloader = new YahooDataDownloader();
            tvsItem.PriceDownloader.Security = tvsItem;
            tvsItem.PriceDownloader.DownloadPricesCompleted += new EventHandler(tvYahoo_DownloadPricesCompleted);
            tvsItem.PriceDownloader.DownloadPrices(tvsItem.LastDownloadTime);
		}
		public void BuildQuery()
		{
			//using sort, start, end and symbols, query the db for each day.
			//place the results in "lite" dayaggregates
			//display those items on the screen.
			//alternatively, actually paint the collection directly.
			//the point is, virtually all functionality is improved via db query.
			if (ivwWatchList.Securities.Count<1)
				return;
				
			string SymbolList=GetSymbolList();
			
			string tvsSort = "";
			switch (ivsSort)
			{
			case SecuritySort.AlphaAZ:
			{
				tvsSort = "Symbols.Symbol ASC";
				break;
			}
			case SecuritySort.AverageGainPCDownPriorClose:
			{
				tvsSort = "AverageGainPercentPriorClose DESC";
				break;
			}
			case SecuritySort.RiseDown:
			{
				tvsSort = "CalcRiseProb DESC";
				break;
			}
            default:
            {
                tvsSort = "Symbols.Symbol ASC";
                break;
            }
			}
			
			
			DateTime tvsDate = ivdSelectionStart.AddDays(1);
			List<DayAggregate> tvdAggs = new List<DayAggregate>();

			DataTier.GetDayAggregatesSortedByDate(tvdAggs, SymbolList, tvsDate.Day, tvsDate.Month, tvsSort);
			
			ivdDayMatrix.Master.AddRange(tvdAggs);
			ivdDayMatrix.Monday.AddRange(tvdAggs);
			
			tvsDate = ivdSelectionStart.AddDays(2);
			tvdAggs = new List<DayAggregate>();

			DataTier.GetDayAggregatesSortedByDate(tvdAggs, SymbolList, tvsDate.Day, tvsDate.Month, tvsSort);
			
			ivdDayMatrix.Master.AddRange(tvdAggs);
			ivdDayMatrix.Tuesday.AddRange(tvdAggs);

			tvsDate = ivdSelectionStart.AddDays(3);
			tvdAggs = new List<DayAggregate>();

			DataTier.GetDayAggregatesSortedByDate(tvdAggs, SymbolList, tvsDate.Day, tvsDate.Month, tvsSort);
			
			ivdDayMatrix.Master.AddRange(tvdAggs);
			ivdDayMatrix.Wednesday.AddRange(tvdAggs);
			
			tvsDate = ivdSelectionStart.AddDays(4);
			tvdAggs = new List<DayAggregate>();

			DataTier.GetDayAggregatesSortedByDate(tvdAggs, SymbolList, tvsDate.Day, tvsDate.Month, tvsSort);
			
			ivdDayMatrix.Master.AddRange(tvdAggs);
			ivdDayMatrix.Thursday.AddRange(tvdAggs);
			
			tvsDate = ivdSelectionStart.AddDays(5);
			tvdAggs = new List<DayAggregate>();

			DataTier.GetDayAggregatesSortedByDate(tvdAggs, SymbolList, tvsDate.Day, tvsDate.Month, tvsSort);
			
			ivdDayMatrix.Master.AddRange(tvdAggs);
			ivdDayMatrix.Friday.AddRange(tvdAggs);
			
		}
		private string GetSymbolList()
		{
			string SymbolList="";
			for (int y=0;y<ivwWatchList.Securities.Count;y++)
				SymbolList+= "'" + ivwWatchList.Securities[y].Symbol + "',";
			return SymbolList.Substring(0, SymbolList.Length-1);
		}

        private void allDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataTier.DeleteAllData();
        }

    }
}
